package com.phy.em.common.shiro.dao;

import java.io.Serializable;
import java.util.Date;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.SimpleSession;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.apache.shiro.subject.Subject;
import org.json.JSONObject;
import org.springframework.transaction.annotation.Transactional;

import com.phy.em.common.dao.IBaseDao;
import com.phy.em.common.shiro.entity.SimpleSessionEntity;
import com.phy.em.user.entity.User;

public class SessionEntityDao extends EnterpriseCacheSessionDAO {
	
	private IBaseDao<User> baseDao;
	private IBaseDao<SimpleSessionEntity> sessionDao;
	private Logger log = Logger.getLogger(SessionEntityDao.class);
	private Serializable sid = null;
	
	@Override
	@Transactional
	public Serializable create(Session session) {
		Serializable cookie = super.create(session);
		SimpleSessionEntity entity = new SimpleSessionEntity();
		entity.setSession((SimpleSession)session);
		entity.setCookie(cookie.toString());
		sessionDao.save(entity);
		
		return cookie;
	}
	
	@Override
	public void update(Session session) throws UnknownSessionException {
		super.update(session);
		SimpleSessionEntity entity = getEntity(session.getId());
		entity.setSession((SimpleSession)session);
		sessionDao.update(entity);
		JSONObject json = new JSONObject(entity);
		System.out.println(json);
		System.out.println("--------------update------------------------------");
	}
	
	
	@Override
	public Session readSession(Serializable sessionId) throws UnknownSessionException {
		// 到了这一步session肯定能找得到，如果没有之前已经创建好了，如果过期了已经被删除，而且已经新建了一个session
		Session session = null;
		
		try{
//			String hql = "from SimpleSessionEntity entity where entity.id ='" + sessionId + "'";
//			SimpleSessionEntity entity =  sessionDao.findUniqueByHQL(hql);
//			session  = (Session) entity.getSession();
//			JSONObject json = new JSONObject(session);
//			System.out.println(json);
//			System.out.println("------------------------------");
			session = super.readSession(sessionId);
//			JSONObject json = new JSONObject(session);
//			log.error(json);
//			log.error("------------------------------");
//			User user = getUser(sessionId);
//			if(user != null){
//				// 如果该用户是APP用户（cookie不为空说明就是），则判断session是否过期，如果过期则修改时间
//				Subject currentUser = SecurityUtils.getSubject();
//				UsernamePasswordToken token = new UsernamePasswordToken(  
//		                user.getPhoneNum(), user.getPassword()); 
//				currentUser.login(token);
//				
//			}
//			String hql = "from SimpleSessionEntity entity where entity.cookie ='" + sessionId + "'";
//			SimpleSessionEntity entity = sessionDao.findUniqueByHQL(hql);
//			session = (Session)entity.getSession();
//			session.setAttribute("user", user);
////			session.setAttribute("", value);
			
		} catch(Exception e){
			
		}
		
		// 如果session已经被删除，则新建一个session
		if(session == null){
//			String hql = "from SimpleSessionEntity entity where entity.id ='" + sessionId + "'";
//			Session entity = (Session) sessionDao.findByHQL(hql);
//			JSONObject json = new JSONObject(entity);
//			System.out.println(json);
//			System.out.println("------------------------------");
//			sid = sessionId;
//			User user = getUser(sessionId);
//			if(user != null){
//				// 如果该用户是APP用户（cookie不为空说明就是），则判断session是否过期，如果过期则修改时间
//				Subject currentUser = SecurityUtils.getSubject();
//				UsernamePasswordToken token = new UsernamePasswordToken(  
//		                user.getPhoneNum(), user.getPassword()); 
//				currentUser.login(token);
//				
//			}
		} else{
			// 如果session没有被删除，则判断session是否过期
			if(isExpire(session)){
				// session过期
				User user = getUser(sessionId);
				if(user != null){
					// 如果该用户是APP用户（user不为空说明就是），则判断session是否过期，如果过期则修改最后访问时间
					((SimpleSession)session).setLastAccessTime(new Date());
				}
			}
		}
		return session;
	}
	
	@Override
	public void delete(Session session) {
		super.delete(session);
		log.error("删除session---------" + session.getId());
		log.error("session总数---------" + super.getActiveSessions().size());
		
	}
	
	private User getUser(Serializable sessionId){
		String hql = "from User user where user.cookie ='" + sessionId + "'";
		return baseDao.findUniqueByHQL(hql);
	}
	
	private SimpleSessionEntity getEntity(Serializable sessionId){
		String hql = "from SimpleSessionEntity entity where entity.cookie ='" + sessionId + "'";
		return sessionDao.findUniqueByHQL(hql);
	}
	
	private boolean isExpire(Session session){
		long timeout = session.getTimeout();
		long lastTime = session.getLastAccessTime().getTime();
		long current = new Date().getTime();
		if((lastTime + timeout) > current){
			return false;
		}
		return true;
	}

	public void setBaseDao(IBaseDao<User> baseDao) {
		this.baseDao = baseDao;
	}

	public void setSessionDao(IBaseDao<SimpleSessionEntity> sessionDao) {
		this.sessionDao = sessionDao;
	}
	
}
